import React, { Component } from 'react'
import "./GoodDetail.css"
import { Carousel, Toast } from 'antd-mobile';
import myaxios from "../../utils/myaxios"

export default class GoodDetail extends Component {
  constructor(props) {
    super(props);
    console.log(props)
  }
  state = {
    detailList: {},
    imgHeight: 176,
    showCollect: false,  // 默认不收藏
    showSwiper: false,
  }

  // 发送请求
  componentDidMount() {
    // 获取地址栏的参数
    let { goods_id } = this.props.match.params;
    // console.log(this.props.match)
    myaxios
      .get("goods/detail", {
        params: {
          goods_id,
        }
      })
      .then(res => {
        // console.log(res)
        // 当请求的轮播图回来的时候  showSwiper true
        this.setState({
          detailList: res,
          showSwiper: true
        })
      })
      .catch((err) => console.log(err))

    // 初次进入商品详情的时候    判断商品是否被收藏
    let collections_str = localStorage.getItem("collections");
    let collections = JSON.parse(collections_str || "[]");
    // 对收藏进行循环遍历
    // 判断是否在收藏中
    let index = collections.findIndex(v => {
      if (v.goods_id == goods_id) {
        return true;
      }
    })
    if (index != -1) {
      this.setState({
        showCollect: true
      })
    }
  }

  // 点击返回上一页
  handleBackClick = (params) => {
    window.history.go(-1)
  }
  // 点击收藏
  handleCollection = (params) => {
    let collections_str = localStorage.getItem("collections");
    let collections = JSON.parse(collections_str || "[]");
    // 对收藏进行遍历
    // 判断是否在收藏中
    let index = collections.findIndex(v => {
      if (v.goods_id === this.state.detailList.goods_id) {
        return true;
      }
    })
    if (index != -1) {
      // 代表之前收藏过
      collections.splice(index, 1);
      Toast.info("取消收藏成功", 1);
      this.setState({
        showCollect: false
      })
    } else {
      Toast.info("收藏成功！", 1);
      collections.push(this.state.detailList);
      this.setState({
        showCollect: true
      })
    }
    localStorage.setItem("collections", JSON.stringify(collections));
  }
  // 去购物车
  handleGoToCart = (params) => {
    this.props.history.push("/cart")
  }
  // 加入购物车 
  handleAddCart = (params) => {
    // console.log(111)
    // 首先从本地缓存中获取购物车的数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]")
    // 获取goods_id
    let {goods_id} = this.props.match.params;
    // 找一下本地缓存中有没有
    let index = carts.findIndex(v=>{
      if(v.goods_id == goods_id){
        return true;
      }
    })
    // 假如没有
    if(index === -1){
      let goods_info = this.state.detailList;
      goods_info.num = 1;   //第一次添加 数量是1  会在缓存中创建一个num记录加购数量
      goods_info.checked = true;   //加入购物车 记录一个值 让他默认为选中状态
      carts.push(goods_info)
    }else{
      carts[index].num ++;  // 第n次添加 
    }
    Toast.info("加入购物车成功!",1)
    localStorage.setItem("carts",JSON.stringify(carts))
  }
  
  // 立即购买
  payNow = (params) => {
    this.props.history.push("/cart")
  }
  



  render() {
    return (
      <div className="yg-detail">
        {/* 头部开始 */}
        <div className="yg-detail-head">
          <i
            className="iconfont icon-fanhui-xianxing"
            onClick={this.handleBackClick}
          ></i>
          <span>商品详情</span>
        </div>
        {/* 头部结束 */}

        {/* 轮播图图片开始 */}
        <div className="yg-detail-swiper">

          {this.state.showSwiper && (
            <Carousel
              autoplay={true}
              infinite
            >
              {this.state.detailList.pics && this.state.detailList.pics.map(val => (
                <div
                  key={val.goods_id}
                  className="imageWrapper"
                  style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                >
                  <img
                    src={val.pics_mid}
                    alt=""
                    style={{ width: '100%', verticalAlign: 'top' }}
                    onLoad={() => {
                      // fire window resize event to change height
                      window.dispatchEvent(new Event('resize'));
                      this.setState({ imgHeight: 'auto' });
                    }}
                  />
                </div>
              ))}
            </Carousel>
          )}
        </div>
        {/* 轮播图图片结束 */}


        {/* 商品价格开始 */}
        <div className="yg-detail-price">
          <div className="price-left">
            <span>￥</span>
            <div className="price">{this.state.detailList.goods_price}</div>
          </div>
          <div className="price-right">
            <i className="iconfont icon-fenxiang_2"></i>
            <i className={this.state.showCollect ? "iconfont icon-shoucang1" : "iconfont icon-shoucang"} onClick={this.handleCollection}></i>
          </div>
        </div>
        {/* 商品价格结束 */}


        {/* 商品标题开始 */}
        <div className="yg-detail-title">
          <span>{this.state.detailList.goods_name}</span>
        </div>
        {/* 商品标题结束 */}

        {/* 图文详情开始 */}
        <div className="yg-detail-richText">
          <div className="richText-title">图文详情</div>
          <div className="richText-content"
            dangerouslySetInnerHTML={{ __html: this.state.detailList.goods_introduce }}

          >
          </div>
        </div>
        {/* 图文详情结束 */}

        {/* 底部按钮组开始 */}
        <div className="yg-detail-bottom">
          <div className="bottom-service">
            <i className="iconfont icon-lianxikefu"></i>
            <span>联系客服</span>
          </div>
          <div className="bottom-cart" onClick={this.handleGoToCart}>
            <i className="iconfont icon-gouwuche1"></i>
            <span>购物车</span>
          </div>
          <div className="bottom-addToCart" onClick={this.handleAddCart}>
            <span>加入购物车</span>
          </div>
          <div className="bottom-buyNow" onClick={this.payNow}>
            <span>立即购买</span>
          </div>
        </div>
        {/* 底部按钮组结束 */}
      </div>
    )
  }
}
